const mongoose = require('mongoose');
const db = 'mongodb://193.112.120.45:27017/lzjgame';
const dbconfig = require('./databaseconfig.json');
const glob = require('glob');
const {resolve} = require('path');

exports.initSchemas = () => {
  glob.sync(resolve(__dirname,'./schema','**/*.js')).forEach(require);
}

exports.connect = () => {
  // 连接数据库
  mongoose.connect(`mongodb://${dbconfig.username}:${dbconfig.password}@${dbconfig.ip}:${dbconfig.port}/${dbconfig.databasename}`, {useFindAndModify: false,useNewUrlParser: true,keepAlive: 120,useUnifiedTopology: true,useCreateIndex: true});
  // bufferCommands: false,
  // 数据库事件监听
  const reConnect = (reject) => {
    let connectMax = 0;
    if(connectMax <= 3) {
      connectMax++;
      mongoose.connect(`mongodb://${dbconfig.username}:${dbconfig.password}@${dbconfig.ip}:${dbconfig.port}/${dbconfig.databasename}`, {useNewUrlParser: true,keepAlive: 120,useUnifiedTopology: true,useCreateIndex: true});  
    } else {
      reject();
      throw new Error("*******数据库连接超时")
    }
  }
  return new Promise((resolve,reject)=> {

    mongoose.connection.on('disconnected',()=> {
      console.log('*******数据库断开');
      reConnect(reject);
    })
    mongoose.connection.on('error',() => {
      console.log('*******数据库错误');
      reConnect(reject);
    })
    mongoose.connection.once('open',() => {
      console.log('*******数据库连接成功');
      resolve();
    })
  })
}
